package com.chenfan.magic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenfan.magic.base.R;
import com.chenfan.magic.base.S;
import com.chenfan.magic.dao.DatasourceMapper;
import com.chenfan.magic.entity.IdcDatasource;
import com.chenfan.magic.entity.Isv;
import com.chenfan.magic.service.IDatasourceService;
import com.chenfan.magic.utils.FastJsonKit;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author troy
 */
@Service
@AllArgsConstructor
public class DatasourceServiceImpl extends ServiceImpl<DatasourceMapper, IdcDatasource> implements IDatasourceService {

    public static final int TWO = 2;

    private DatasourceMapper datasourceMapper;

    @Override
    public void updateApplyTime(String id) {
        datasourceMapper.updateApplyTime(id);
    }

    /**
     * 获取应用数据源列表
     *
     * @param isv
     * @return
     */
    @Override
    public R get(Isv isv) {
        Integer envir = isv.getAppEnvir();
        if (null == envir) {
            return S.fail(S.IDC_ENVIR_CODE_NULL);
        }
        //1.根据环境状态获取对应的数据源JSON串
        String json = "";
        if (0 == envir) {
            json = isv.getAppDatasourcesDev();
        } else if (1 == envir) {
            json = isv.getAppDatasourcesTest();
        } else if (TWO == envir) {
            json = isv.getAppDatasourcesProd();
        } else {
            return S.fail(S.IDC_ENVIR_CODE_INVAILD);
        }
        //自定义索引->数据源实体
        Map<String, IdcDatasource> dsMap = Maps.newHashMap();
        //基于下面的算法, 数据源宜少不宜多, 此算法后期待优化.
        //自定义索引->数据源id
        Map<String, String> dsIdMap = FastJsonKit.jsonstring2Map(json);
        Iterator<Map.Entry<String, String>> iterator = dsIdMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> kv = iterator.next();
            //注意: 一个主数据源, 多个从数据源
            String key = kv.getKey();
            String value = kv.getValue();
            IdcDatasource idcDatasource = this.getById(value);
            if (idcDatasource == null) {
                return S.fail(S.IDC_DATASOURCE_NULL, " => " + value);
            } else {
                if (0 == idcDatasource.getStatus()) {
                    //判断数据源类型是否合法
                    dsMap.put(key.toLowerCase(), idcDatasource);
                } else {
                    return S.fail(S.IDC_DATASOURCE_FORBIDDEN, " => " + value);
                }
            }
        }
        if (MapUtils.isEmpty(dsMap)) {
            return S.fail(S.IDC_DATASOURCE_GROUP_EMPTY);
        }
        return R.success().put(dsMap);
    }
}
